<?php

declare(strict_types=1);

namespace App\Third\Service\Lsy;

use App\Common\Constants\ErrorCode;
use App\Common\Service\BaseService;
use App\Resource\Model\ShopModel;
use App\Resource\Service\BuildGoodsService;
use App\Third\Task\InsertLsyStockTask;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\Parallel;

class PullLsyStockService extends BaseService
{
    public function pullLsyStockToRedis()
    {
        $lsyShopMap = ShopModel::query()->pluck('lsy_shop_no', 'shop_id')->toArray();
        $container = $this->container;
        $redis = $this->buildRedis;
        $parallel = new Parallel(30);
        foreach ($lsyShopMap as $shop_id => $lsy_shop_no){
            $parallel->add(function () use ($container,$shop_id,$lsy_shop_no) {
                $stock = $container->get(LsyMainGoodsService::class)->completeShopPullArchInfoStock((int)$lsy_shop_no);
//                $stock = json_decode(file_get_contents(BASE_PATH . "/runtime/list-{$shop_id}.php"), true);
                $map = [];
                if (!empty($stock) && $stock['count'] > 0) {
                    foreach ($stock['itemList'] as $v) {
                        $map += [$v['itemId'] => $v['surplusQuantity']];
                    }
                }
                return ['key' => $lsy_shop_no, 'map' => $map];
            });
        }
        try {
            $res = $parallel->wait();
            $pip = $redis->multi(2);
            foreach ($res as $k => $v){
                $pip->del("lsy:{$v['key']}:stock");
                if (empty($v['map'])) continue;
                $pip->hMSet("lsy:{$v['key']}:stock", $v['map']);
            }
            $pip->exec();
            $container->get(BuildGoodsService::class)->buildAllShopTimelyGoodsListToRedis($lsyShopMap);
            $container->get(InsertLsyStockTask::class)->handle();
        }catch (\Exception $e){
            $container->get(LoggerFactory::class)
                ->get('库存异常','LsyShopGoodsStockTask')
                ->error("库存缓存更新异常", ['params' => $lsyShopMap, 'error' => $e->getMessage()]);
        }
        return true;
    }

    public function delKeys(){
        try {
            $redis = $this->buildRedis;
            $iterator = null;
            $dels = [];
            while(false !== ($del = $redis->scan($iterator,"lsy:*:stock"))) {
                foreach($del as $v) {
                    array_push($dels, $v);
                }
            }
            $count = $redis->del($dels);
            return ['code' => 1, 'data'=>['key_num' => $count], 'msg' => '清空龙收银库存缓存成功'];
        }catch (\Exception $e){
            return ['code' => 0, 'errorCode' => ErrorCode::SYSTEM_INVALID, 'msg' => $e->getMessage()];
        }
    }

    public function lsyStockDataCount(){
        $redis = $this->buildRedis;
        $iterator = null;
        $keys = [];
        $len = [];
        while(false !== ($key = $redis->scan($iterator,"lsy:*:stock"))) {
            foreach($key as $v) {
                array_push($keys, $v);
            }
        }
        foreach ($keys as $v) array_push($len, $redis->hLen($v));
        return array_sum($len);
    }

    public function lsyStockAllData() :array {
        $redis = $this->buildRedis;
        $iterator = null;
        $data = [];
        while(false !== ($keys = $redis->scan($iterator,"lsy:*:stock"))) {
            foreach($keys as $v) {
                $lsy_shop_no = explode(':', $v)[1];
                foreach ($redis->hGetAll($v) as $crm_goods_id => $stock){
                    $data[] = [
                        'itemId' => $crm_goods_id,
                        'createShopId' => $lsy_shop_no,
                        'surplusQuantity' => $stock,
                    ];
                }
            }
        }
        return $data;
    }

}
